"""扩展模块. 每个扩展在app.py里初始化"""
from flask_bcrypt import Bcrypt
from flask_caching import Cache
from flask_httpauth import HTTPTokenAuth
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
from flask import jsonify, make_response, g

from app.weixin import Weixin

auth = HTTPTokenAuth(scheme='Bearer')
bcrypt = Bcrypt()
cache = Cache(config={'CACHE_TYPE': 'simple'})
db = SQLAlchemy()
migrate = Migrate()
wx = Weixin()


def roles_accepted(*roles):
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = g.user.role in roles
            if perm:
                return fn(*args, **kwargs)
            return make_response(jsonify({'message': 'Unauthorized access'}), 403)
        return decorated_view
    return wrapper

